package com.wobito.system.task;

import cn.hutool.core.collection.CollectionUtil;
import com.wobito.common.utils.DateUtils;
import com.wobito.pojo.bean.Borrow;
import com.wobito.pojo.enums.BorrowStatusEnum;
import com.wobito.service.DbService;
import com.wobito.service.IBorrowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lambyang
 * @version 1.0
 * @Create 2024/9/13 9:49
 * @Description 定时任务
 */
@Component
@Slf4j
public class TimingManageTask {

    @Autowired
    private IBorrowService borrowService;
    @Autowired
    private DbService dbService;

    /**
     * 定时任务 每晚2:30盘点借阅时间是否逾期
     */
    @Scheduled(cron = "0 30 2 * * ?")
    public void taskInventoryBorrowBook() {
        List<Borrow> borrowList = borrowService.list();
        if (CollectionUtil.isNotEmpty(borrowList)) {
            List<Borrow> normalBorow = new ArrayList<>();
            List<Borrow> renewBorow = new ArrayList<>();
            for (Borrow borrow : borrowList) {
                if (borrow.getRenewDay() == null && borrow.getRenewTime() == null) {
                    normalBorow.add(borrow);
                } else {
                    renewBorow.add(borrow);
                }
            }
            if (CollectionUtil.isNotEmpty(normalBorow)) {
                List<Borrow> updateNobList=new ArrayList<>();
                for (Borrow nob : normalBorow) {
                    if (DateUtils.isDateBefore(DateUtils.getNowDate(),nob.getDueTime())){
                        nob.setStatus(BorrowStatusEnum.OVERDUE.getCode());
                        updateNobList.add(nob);
                    }
                }
                borrowService.updateBatchById(updateNobList);
            }
            if (CollectionUtil.isNotEmpty(renewBorow)) {
                List<Borrow> updateRenList=new ArrayList<>();
                for (Borrow ren : normalBorow) {
                    if (DateUtils.isDateBefore(DateUtils.getNowDate(),ren.getRenewTime())){
                        ren.setStatus(BorrowStatusEnum.OVERDUE.getCode());
                        updateRenList.add(ren);
                    }
                }
                borrowService.updateBatchById(updateRenList);
            }
        }
        log.info(DateUtils.getTime() + "执行借阅信息是否逾期盘点成功");
    }

    /**
     * 定时任务 每月1号晚上2:00创建日志表
     */
    @Scheduled(cron = "0 0 2 1 * ?")
    public void taskDelLog() {
        dbService.createNewTable(DateUtils.getYearAndMonth());
    }
}